/*
 * PhoneProfile.java
 *
 * Created on February 2, 2009, 5:22 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.vacuela.phonecredits;

import com.u2d.app.Context;
import com.u2d.model.AbstractComplexEObject;
import com.u2d.model.Title;
import com.u2d.type.atom.StringEO;
import java.awt.Color;

import com.u2d.app.User;
import com.u2d.element.CommandInfo;
import com.u2d.model.ComplexType;
import com.u2d.persist.HBMSingleSession;
import com.u2d.reflection.Arg;
import com.u2d.type.atom.*;
import java.util.Date;
import com.u2d.reflection.Cmd;
import com.u2d.type.composite.LoggedEvent;
import com.vacuela.phonecredits.util.FileUtil;
import java.io.File;

import com.u2d.reporting.ReportFormat;
import com.u2d.reporting.Reportable;
import java.util.List;
import javax.swing.table.TableModel;
import java.util.Properties;
/**
 *
 * @author nestor.carrasco
 */

public class PhoneProfile extends AbstractComplexEObject{
    private final StringEO _phoneNumber = new StringEO();
    private final StringEO _nip = new StringEO();
    private final FloatEO _saldo = new FloatEO();
    private final DateEO _telcelDate = new DateEO();
    private final TimeEO _telcelTime = new TimeEO();
    private final DateTime _cronUpdate = new DateTime();
    private User _registeredBy ;
    private final DateTime _registeredDate = new DateTime(new Date());
    protected final Owner _owner = new Owner();
    private  Location _location = null;
    private final StringEO _simNumber = new StringEO();
    
    public static String locationInverseFieldName ="phones";
    public static String[] fieldOrder =   {"number", "nip","saldo","simNumber","location","telcelDate","telcelTime","cronUpdate","registeredBy","registeredDate","owner"};
    public static String[] tabViews = {"owner"};
    public static String[] readOnly = {"saldo","telcelDate","telcelTime","cronUpdate","registeredBy","registeredDate"};
    public static String[] identities = {"number"};
    public static Color colorCode = new Color(0x4169aa);
    public static String defaultSearchPath ="number";
    
    
    public void initialize() {
        _registeredBy = currentUser();
    }
    
    public PhoneProfile() {}
    
    public PhoneProfile(String number, String nip,String sim){
        _phoneNumber.setValue(number);
        _nip.setValue(nip);
		_simNumber.setValue(sim);
    }
    
    public StringEO getNumber() {
        return _phoneNumber;
    }
    
    public StringEO getNip(){
        return _nip;
    }
    
    public FloatEO getSaldo(){
        return _saldo;
    }
    
    public DateEO getTelcelDate(){
        return _telcelDate;
    }
    
    
    public TimeEO getTelcelTime(){
        return _telcelTime;
    }
    public DateTime getCronUpdate(){
        return _cronUpdate;
    }
    public User getRegisteredBy(){
        return _registeredBy;
    }
    
    public void setRegisteredBy(User user) {
        User oldRes = _registeredBy;
        _registeredBy = user;
        firePropertyChange("registeredBy", oldRes, _registeredBy);
    }
    
    public Owner getOwner(){
        return _owner;
    }
//    public void setOwner(Owner newOwner){
//        Owner old = _owner;
//        _owner = newOwner;
//        firePropertyChange("owner",old,_owner);
//    }
    
    public DateTime getRegisteredDate(){
        return _registeredDate;
    }
    
    public StringEO getSimNumber(){
        return _simNumber;
    }
    
    public Title title() {
        
        return _phoneNumber.title().append("[Nip:").append(_nip).append("]")
        .append("[Sim:").append(_simNumber).append("]")
        .append("[Saldo:").append(_saldo).append("]");
        
    }
    public String toString() {
        return title().toString();
    }
    
    public Location getLocation() {
        return _location;
    }
    
    public void setLocation(Location newLocal){
        Location old = _location;
        _location = newLocal;
        firePropertyChange("location",old,_location);
    }
    @Cmd
    public static Object ImportFromExcel(CommandInfo cmdInfo, @Arg("File Location") FileEO basePath)  {
        File selectedFile = basePath.fileValue();
        List<PhoneProfile> phoneList = null;
        
        if (selectedFile.isDirectory() || !selectedFile.exists()){
            return "You must specify a Excel File";
        }
        
        
        phoneList = FileUtil.readPhonesFromFile(selectedFile.getAbsolutePath());
        int goodCounter = 0,
            badCounter = 0;
        if ( null != phoneList && phoneList.size() > 0){
            HBMSingleSession pmech = (HBMSingleSession)  Context.getInstance().getPersistenceMechanism();
            for(PhoneProfile phone:phoneList){
                try{
                    pmech.save(phone);
                    ++goodCounter;
                }catch(Exception e){
                    Context.getInstance().getApplication().log(LoggedEvent.ERROR, cmdInfo.getCommand(), "Exception during Saving =>> " +
                            phone.getNumber() + " - " + phone.getNip()+" --> " + e);
                    ++badCounter;
                }
            }
            Context.getInstance().getApplication().log(LoggedEvent.INFO, cmdInfo.getCommand(), 
                    "Imported Total: " + phoneList.size() + " Saved Correctly: " + goodCounter + " Wrong: " + badCounter);
            // pmech.saveMany(phoneSet);
        }
        
        
        
        return "Please see the Logged Event";
    }
    
    public boolean equals(Object obj)  {
        if (obj == null)
            return false;
        if (!(obj instanceof PhoneProfile))
            return false;
        PhoneProfile phone = (PhoneProfile) obj;
        return _phoneNumber.equals(phone.getNumber());
    }
    
    public int hashCode() {
        return this._phoneNumber.hashCode();
    }
    
    @Cmd
    public static Reportable Report(CommandInfo cmdInfo)  {
        
        return new Reportable() {
            public String reportName() {
                return "com/vacuela/phonecredits/BasicPhoneList.xml";
            }
            public Properties properties() {
                return new Properties();
            }
            public ReportFormat reportFormat() {
                return ReportFormat.PDF;
            }
            
            
            public TableModel tableModel() {
                return ComplexType.forClass(PhoneProfile.class).list().tableModel();
            }
        };
    }
    
}